<template>
    <transition>
        <el-dialog :title="dialogType === 'add' ? '添加系部试卷申请' : '修改系部试卷申请'" v-model="showFlag" width="600px"
            append-to-body @close="handleClose" @open="handleOpen">
            <el-form hide-required-asterisk ref="formRef" :rules="formRule" :model="formInfo" label-width="auto"
                style="padding:30px 30px 0 30px">
                <el-form-item label="课程名称" prop="courseName">
                    <el-select placeholder="课程名称" v-model="formInfo.courseName">
                        <el-option v-for="e in courses" :key="e" :value="e.id" :label="e.courseName"></el-option>
                    </el-select>
                </el-form-item>
                <el-upload :action="config.UPLOAD_BASE_URL" :headers="{ token: token }"
                    :on-success="handleUploadSuccess" :limit="1" show-file-list="true" style="margin-top: 20px;">
                    <el-button type="primary">上传文件</el-button>
                </el-upload>
                <el-form-item style="margin-top: 40px; margin-left: 372px; ">
                    <el-button @click="handleClose" size="mini">取消</el-button>
                    <el-button @click="formSubmit" size="mini" type="primary">确定</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </transition>
</template>

<script setup>
import api from '@/api/api';
import { ElMessage } from 'element-plus';
import { onMounted, reactive, ref, watch } from 'vue';
import config from '@/config/index'

const props = defineProps({
    dialogType: {
        type: String,
        default: 'add'
    }, showDialog: {
        type: Boolean
    },
    applyId: {
        default: ''
    },
    editForm: {
        type: Object
    }
})
const emit = defineEmits(['dialogClosed'])
const showFlag = ref(false)

const courses = ref([
    // courseId, courseName, className
])
const paperContent = ref(null)
const token = ref(null)

const formRef = ref(null)

const formRule = ref({
    courseName: [
        { required: true, message: '请填写课程名称', trigger: 'blur' }
    ],
})
const formInfo = reactive(
    {
        'courseName': '',
    },
)
const formSubmit = () => {
    formRef.value.validate((valid) => {
        if (valid) {
            if (props.dialogType == 'add') {
                api.exampaper_application.add(
                    formInfo.courseName, sessionStorage.getItem('userid'), paperContent.value
                ).then((res) => {
                    ElMessage({
                        message: '添加成功',
                        type: 'success'
                    })
                }).catch((err) => {
                    console.log(err)
                })

                handleClose()
            } else {
                api.exampaper_application.edit(props.applyId,
                    formInfo.courseName, sessionStorage.getItem('userid'), paperContent.value
                ).then((res) => {
                    ElMessage({
                        message: '修改成功',
                        type: 'success'
                    })
                }).catch((err) => {
                    console.log(err)
                })

                handleClose()
            }

        }
    })
}
const handleClose = () => {
    showFlag.value = false
    formRef.value.resetFields()
    emit('dialogClosed')
}
const handleOpen = () => {
    if (props.dialogType === 'edit') {
        formInfo.courseName = props.editForm.courseName
    }
}
const handleUploadSuccess = (res) => {
    paperContent.value = res.data
}

watch(() => props.showDialog, (newValue, oldValue) => {
    showFlag.value = props.showDialog
})


onMounted(() => {
    api.scheduled_course.get_all().then((res) => {
        let base_courses = res.data.data
        let course_set = new Set()
        for (let i = 0; i < base_courses.length; i++) {
            // 排课后一个course对应不同class，因此会有重复course
            // 所以需要筛掉重复的course
            if (!course_set.has(base_courses[i].courseId)) {
                course_set.add(base_courses[i].courseId)
                courses.value.push(base_courses[i])
            }
        }
    }).catch((err) => {
        console.log(err)
    })
    token.value = sessionStorage.getItem('token')
})
</script>